<!-- 修改后的PestList.vue -->
<template>
  <div class="container">
    <!-- 列表视图 -->
    <div v-if="!currentPest">
      <div class="header">
        <h2>病虫害监测{{ farmlandId }}</h2>
        <el-button @click="goBack" type="primary">返回农田列表</el-button>
      </div>
      <el-table :data="pestData" style="width: 100%">
        <el-table-column prop="pest_id" label="病虫害ID" width="120" />
        <el-table-column prop="pest_type" label="类型" />
        <el-table-column prop="severity" label="影响程度" />
        <el-table-column prop="affected_area" label="影响面积(亩)" />
        <el-table-column prop="timestamp" label="检测时间" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { getPestDiseaseData } from '@/api/farmland'

const route = useRoute()
const router = useRouter()

const farmland_id = computed(()=>route.params.farmland_id)
const currentPest = ref(null)
const pestData = ref([])
// 返回农田列表
const goBack = () => {
  router.push('/farmland/pest')
}
onMounted(async () => {
  // 从后端获取数据
  // axios.get('http://10.25.160.244:5000/pestdisease/getPestDiseaseData/?farmlandId=2')
  //   .then(response => {
  //     console.log(response.data.data[0])
  //     pestData.value = response.data.data[0]
  //   })
  //   .catch(error => {
  //     console.error('Error fetching data:', error)
  //   })
    try {
      console.log(farmland_id.value)
      let response = await getPestDiseaseData(farmland_id.value)
      console.log(response)
      pestData.value = response.data[0]
    }catch(err){
      console.error('Error fetching data:', err)
    }
})
watch(
  () => route.params.pestId,
  (newVal) => {
    if (newVal) {
      currentPest.value = pestData.value.find(
        item => item.id.toString() === newVal && 
                item.farmId === route.params.farmId
      )
    } else {
      currentPest.value = null
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.detail-view {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 30px;
}

.action-btns {
  margin-top: 30px;
  text-align: center;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>